﻿using System.IO;
using System.IO.Compression;
using System.Text;

namespace BridgeWebSystemLib.Core.Util
{
    public static class CompressionUtil
    {
        public static byte[] DeflateCompress(byte[] bytes)
        {
            if (bytes == null)
            {
                return null;
            }
            using (var output = new MemoryStream())
            {
                using (var compressor = new DeflateStream(output, CompressionMode.Compress))
                {
                    compressor.Write(bytes, 0, bytes.Length);
                }
                return output.ToArray();
            }
        }

        public static string DeflateDecompress(byte[] bytes)
        {
            using (MemoryStream ms = new System.IO.MemoryStream(bytes))
            {
                using (DeflateStream stream = new DeflateStream(ms, CompressionMode.Decompress))
                {
                    stream.Flush();
                    byte[] decompressBuffer = ToByteArray(stream);
                    int nSizeIncept = decompressBuffer.Length;
                    stream.Close();
                    //转换为普通的字符串
                    return Encoding.UTF8.GetString(decompressBuffer, 0, nSizeIncept);   
                }
            }
        }

        private static byte[] ToByteArray(Stream stream)
        {
            byte[] buffer = new byte[32768];
            using (MemoryStream ms = new MemoryStream())
            {
                while (true)
                {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                        return ms.ToArray();
                    ms.Write(buffer, 0, read);
                }
            }
        }

        public static byte[] GZipByte(byte[] bytes)
        {
            if (bytes == null)
            {
                return null;
            }
            using (var output = new MemoryStream())
            {
                using (var compressor = new GZipStream(output, CompressionMode.Compress))
                {
                    compressor.Write(bytes, 0, bytes.Length);
                }
                return output.ToArray();
            }
        }
    }
}
